<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px;">
      <detail-list title="基本信息">
        <detail-list-item term="活动编号">{{ info.id }}</detail-list-item>
        <detail-list-item term="状态">{{ status }}</detail-list-item>
        <detail-list-item term="商品名称">{{ info.commodity && info.commodity.name }}</detail-list-item>
        <detail-list-item term="商品编号">{{ info.commodity && info.commodity.numbering }}</detail-list-item>
      </detail-list>
    </a-card>

    <a-card :bordered="false">
      <a-descriptions title="转发素材">
        <a-descriptions-item label="推送设置" v-if="!state.isEdit" :span="3">{{ pushSetting }}</a-descriptions-item>
        <a-descriptions-item label="素材内容" v-if="!state.isEdit" :span="3">
          <a-descriptions layout="vertical">
            <a-descriptions-item v-for="(item) in info.materials" :key="item.id" :label="materialType[item.type]">
              <span v-if="item.type !== 2">
                {{ item.content }}
              </span>
              <span v-else>
                <img width="100" :src="item.attachments[0].url"/>
              </span>
            </a-descriptions-item>
          </a-descriptions>
        </a-descriptions-item>
      </a-descriptions>

      <a-form ref="form" :form="form" v-show="state.isEdit" @submit="handleSubmit">
        <a-form-item
          label="推送设置"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-radio-group
            v-decorator="['push_setting', { initialValue: 1 }]">
            <a-radio value="1">不推送</a-radio>
            <a-radio value="2">立即推送</a-radio>
            <a-radio value="3">定时推送</a-radio>
            <a-radio value="4">每日推送</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item v-show="form.getFieldValue('push_setting') === '3'" :wrapperCol="{ offset: 2 }">
          <a-date-picker
            v-decorator="['specify_the_push_date', { rules: [{ required: true, message: '请选择时间' }] }]"
            :show-time="{ format: 'HH:mm' }"
            format="YYYY-MM-DD HH:mm"
          />
        </a-form-item>

        <a-form-item v-show="form.getFieldValue('push_setting') === '4'" :wrapperCol="{ offset: 2 }">
          <a-time-picker
            v-decorator="['specify_the_push_time', { rules: [{ required: true, message: '请选择时间' }] }]"
            format="HH:mm"
          />
        </a-form-item>

        <a-form-item
          label="素材内容"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-row type="flex" justify="start" :gutter="16">
            <a-col>
              <a-button type="link" icon="plus" @click="addMaterial(1, 0)">文字素材</a-button>
            </a-col>
            <a-col>
              <a-button type="link" icon="plus" @click="addMaterial(2, 0)">图片素材</a-button>
            </a-col>
            <a-col>
              <a-button type="link" icon="plus" @click="addMaterial(3, 0)">视频链接</a-button>
            </a-col>
          </a-row>
        </a-form-item>

        <div>
          <!--material 得手动排下序-->
          <a-form-item
            v-for="(id, index) in material"
            :key="id"
            :label="`${(index + 1)} . ${materialType[materialDetail[id].type]}`"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-row type="flex" justify="start" :gutter="16">
              <a-col span="15">
                <a-textarea
                  v-if="materialDetail[id].type === 1"
                  v-decorator="[`material[${id}]`, { rules: [{ type: 'string', required: true, message: '请填写文字素材' }] }]"
                />

                <upload-pic
                  v-if="materialDetail[id].type === 2"
                  :limit="1"
                  wechat-material
                  v-decorator="[`material[${id}]`, { rules: [{ type: 'array', required: true, message: '请上传图片素材' }], initialValue: [] }]"
                />

                <a-input
                  v-if="materialDetail[id].type === 3"
                  v-decorator="[`material[${id}]`, { rules: [{ type: 'string', required: true, message: '请填写视频链接' }] }]"
                />
              </a-col>
              <a-col style="display: flex; align-items: center;">
                <a-icon
                  :style="{ fontSize: '25px', 'margin-right': '10px' }"
                  type="minus-circle"
                  @click="delMaterial(id)"/>

                <a-popover trigger="click">
                  <span slot="content">
                    <a-row type="flex" justify="start" :gutter="16">
                      <a-col>
                        <a-button type="link" icon="plus" @click="addMaterial(1, id)">文字素材</a-button>
                      </a-col>
                      <a-col>
                        <a-button type="link" icon="plus" @click="addMaterial(2, id)">图片素材</a-button>
                      </a-col>
                      <a-col>
                        <a-button type="link" icon="plus" @click="addMaterial(3, id)">视频链接</a-button>
                      </a-col>
                    </a-row>
                  </span>

                  <a-icon :style="{ fontSize: '25px' }" type="plus-circle"/>
                </a-popover>
              </a-col>
            </a-row>
          </a-form-item>
        </div>

        <a-form-item>
          <a-button type="primary" htmlType="submit" :loading="state.submitLoading">保存</a-button>
        </a-form-item>
      </a-form>

      <a-button
        type="primary"
        @click="handleEdit"
        v-show="!state.isEdit"
      >编辑
      </a-button>
    </a-card>
  </div>
</template>

<script>
  import DetailList from '@/components/DescriptionList/DescriptionList'
  import { getCommodityActivityLiveTodayInfo, saveCommodityActivityLiveTodayMaterialSettings } from '@/api/commodity'
  import moment from 'moment'
  import UploadPic from '@/components/UploadPic/UploadPic'
  import Vue from 'vue'

  // eslint-disable-next-line no-unused-vars
  const DetailListItem = DetailList.Item

  const STATUS_MAP = {
    1: '已上架',
    2: '已下架'
  }

  const PUSH_SETTING = {
    1: '不推送',
    2: '立即推送',
    3: '定时推送',
    4: '每日推送'
  }

  const MATERIAL_TYPE = {
    1: '文字',
    2: '图片',
    3: '视频链接'
  }

  let currentSelfIncreasingMaterialId = 10

  export default {
    name: 'ForwardMaterial',
    components: { UploadPic, DetailList, DetailListItem },
    computed: {
      status () {
        let status = STATUS_MAP[this.info.status]
        if (!moment().isBetween(moment(this.info.panic_buying_start_time), moment(this.info.panic_buying_end_time))) {
          status = '已结束'
        }
        return status
      },
      pushSetting () {
        let setting = PUSH_SETTING[this.info.push_setting]
        if (this.info.push_setting === 3) {
          setting += (': ' + this.info.specify_the_push_date + ' ' + this.info.specify_the_push_time)
        } else if (this.info.push_setting === 4) {
          setting += (': ' + this.info.specify_the_push_time)
        }
        return setting
      }
    },
    data () {
      return {
        labelCol: {
          xs: { span: 2 },
          sm: { span: 2 }
        },
        wrapperCol: {
          xs: { span: 12 },
          sm: { span: 12 }
        },
        form: this.$form.createForm(this),

        queryParam: {},
        info: {},
        state: {
          isEdit: false,
          submitLoading: false
        },
        material: [],
        materialDetail: {},
        materialType: MATERIAL_TYPE
      }
    },
    created () {
      if (this.$route.params.id) {
        this.getCommodityActivityLiveTodayInfo()
      }
    },
    methods: {
      handleSubmit (e) {
        e.preventDefault()
        if (this.material.length === 0) {
          this.$message.error('请添加推送素材')
          return false
        }
        this.state.submitLoading = true

        this.form.validateFields((err, val) => {
          if (err) {
            this.state.submitLoading = false
            return false
          }

          const values = val
          typeof values.specify_the_push_date === 'object' && (values.specify_the_push_date = values.specify_the_push_date.format('YYYY-MM-DD HH:mm:ss'))
          typeof values.specify_the_push_time === 'object' && (values.specify_the_push_time = values.specify_the_push_time.format('HH:mm'))
          // 根据 material 获取值
          const materialTemp = values.material
          values.material = []
          this.material.forEach(id => {
            values.material.push({
              type: this.materialDetail[id].type,
              value: this.materialDetail[id].type === 2 ? materialTemp[id].map(att => att.response.id) : materialTemp[id] // 图片类型
            })
          })

          saveCommodityActivityLiveTodayMaterialSettings(this.$route.params.id, values)
            .then(res => {
              this.getCommodityActivityLiveTodayInfo()
                .finally(_ => {
                  this.state.submitLoading = false
                  this.state.isEdit = false
                  this.$notification.success({ message: '保存成功!' })
                })
            })
            .catch(_ => {
              this.state.submitLoading = false
            })
        })
      },
      /**
       * 添加素材
       * @param type 类型
       * @param id 要在这个 id 下加入素材
       */
      addMaterial (type, id = null) {
        if (id === null) {
          id = currentSelfIncreasingMaterialId
          currentSelfIncreasingMaterialId++
        } else {
          let nextid = '0' // 找下一个值
          if (id === 0) {
            // 如果 id 为零,表示要加在头部
            this.material.hasOwnProperty(0) && (nextid = this.material[0])
          } else {
            const idInMaterial = this.material.indexOf(id) // 提交的 id 在 material 里的位置
            if (this.material.hasOwnProperty(idInMaterial + 1)) {
              nextid = this.material[idInMaterial + 1]
            }
          }
          if (nextid === '0') {
            // 为零的话 说明当前是最后一个, 直接走原来逻辑
            id = currentSelfIncreasingMaterialId
            currentSelfIncreasingMaterialId++
          } else {
            // 中间的情况,取中间值
            id = (parseFloat(id) + parseFloat(nextid)) / 2
          }
        }

        Vue.set(this.materialDetail, id, { type })
        this.material.push(id)
        this.material.sort((a, b) => a - b) // 排序
      },
      delMaterial (id) {
        Vue.delete(this.material, this.material.indexOf(id))
        Vue.delete(this.materialDetail, id)
      },
      handleEdit () {
        this.state.isEdit = true
        // 初始化
        this.material = [] // 对象属性不保证顺序,用不了 key 排序,这里用数组排序
        this.materialDetail = {}

        const res = this.info

        res.materials.forEach(item => {
          this.addMaterial(item.type)
        })

        this.$nextTick(_ => {
          this.form.setFieldsValue({
            push_setting: res.push_setting.toString(),
            specify_the_push_date: (res.specify_the_push_date && res.specify_the_push_time && moment(res.specify_the_push_date + ' ' + res.specify_the_push_time)) || moment(),
            specify_the_push_time: (res.specify_the_push_time && (moment(moment().format('YYYY-MM-DD') + ' ' + res.specify_the_push_time))) || moment()
          })

          let currentMaterialId = currentSelfIncreasingMaterialId - res.materials.length
          res.materials.map(item => {
            if (item.type === 2) { // 图片类型
              const pic = item.attachments[0]
              this.form.setFieldsValue({
                [`material[${currentMaterialId}]`]: [{
                  url: pic.url,
                  response: { id: pic.id, url: pic.url },
                  mime_type: pic.mime_type || '',
                  uid: pic.id,
                  name: pic.id.toString()
                }]
              })
            } else {
              this.form.setFieldsValue({
                [`material[${currentMaterialId}]`]: item.content
              })
            }

            currentMaterialId++
          })
        })
      },
      getCommodityActivityLiveTodayInfo () {
        return new Promise((resolve, reject) => {
          getCommodityActivityLiveTodayInfo(this.$route.params.id).then(res => {
            this.info = res
          }).finally(_ => resolve())
        })
      }
    }
  }
</script>

<style lang="less" scoped>

</style>
